/* -*- c++ -*- */
/*
 * Copyright 2005 Free Software Foundation, Inc.
 * 
 * This file is part of GNU Radio
 * 
 * GNU Radio is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 * 
 * GNU Radio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with GNU Radio; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "lpc_lpc10_vbr_decoder.h"
#include "lpc10/lpc10.h"
#include <gr_io_signature.h>
#include <stdexcept>
#include <assert.h>

lpc_lpc10_vbr_decoder_sptr
lpc_make_lpc10_vbr_decoder ()
{
  return lpc_lpc10_vbr_decoder_sptr (new lpc_lpc10_vbr_decoder ());
}

lpc_lpc10_vbr_decoder::lpc_lpc10_vbr_decoder ()
  : gr_block ("lpc_lpc10_vbr_decoder",
			  gr_make_io_signature (1, 1, sizeof (char)),
			  gr_make_io_signature (1, 1, sizeof (short)))
{
  set_fixed_rate (false);

  if ((d_lpc10 = create_lpc10_decoder_state ()) == 0)
    throw std::runtime_error ("lpc_lpc10_vbr_decoder: create_lpc10_decoder_state failed");

  init_lpc10_decoder_state (d_lpc10);
}

lpc_lpc10_vbr_decoder::~lpc_lpc10_vbr_decoder ()
{
  destroy_lpc10_decoder_state (d_lpc10);
}

int
lpc_lpc10_vbr_decoder::general_work (int noutput_items,
			gr_vector_int &ninput_items,
            gr_vector_const_void_star &input_items,
			gr_vector_void_star &output_items)
{
  const unsigned char *in = (const unsigned char *) input_items[0];
  short *out = (short *) output_items[0];

  int len = 0, inoff = 0;

  while (len < noutput_items && inoff < ninput_items[0]) {
    int p = 0;
    vbr_lpc10_decode (const_cast<unsigned char*>(in+inoff), out+len, d_lpc10, &p);
    inoff += p;
    len += LPC10_SAMPLES_PER_FRAME;
  }

  consume_each (inoff);

  return len;
}

void
lpc_lpc10_vbr_decoder::forecast (int noutput_items,
      gr_vector_int &ninput_items_required)
{
  unsigned ninputs = ninput_items_required.size ();
  for (unsigned i = 0; i < ninputs; i++)
    ninput_items_required[i] = std::max(1, noutput_items / LPC10_SAMPLES_PER_FRAME);
}
